import { Provide, Inject } from '@midwayjs/decorator';
import { BaseService, CoolEventManager } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { UserNotifyEntity } from '../entity/notify';
import { ImSocketEvent } from '../../im/socket/event';

/**
 * 描述
 */
@Provide()
export class UserNotifyService extends BaseService {
  @InjectEntityModel(UserNotifyEntity)
  userNotifyEntity: Repository<UserNotifyEntity>;

  @Inject('cool:coolEventManager')
  coolEventManager: CoolEventManager;

  @Inject()
  imSocketEvent: ImSocketEvent;

  async save(pm: any) {
    const data = await this.userNotifyEntity.save(pm);
    this.coolEventManager.emit('putMessage', data);
  }

  /**
   * 已读
   * @param Ids
   * @param isRead
   * @param userId
   */
  async read(Ids: number[], isRead: number, userId: number) {
    return  await this.userNotifyEntity
      .createQueryBuilder()
      .update()
      .set({ isRead })
      .where('userId =:userId', { userId })
      .andWhere('id in (:Ids)', { Ids })
      .execute();
  }

  /**
   * 未读统计
   */
  async unCount(userId: number) {
    // 根据id查询 未读消息记录数量
    return await this.userNotifyEntity.count({ userId: userId, isRead: 0 });
  }
}
